<?php
// 图片相关函数

/*输出图片*/
function img($id): string
{
	$img = query("img", " id = '$id' ");
	return root . $img['src'] . "?time=" . strtotime($img['updateTime']);
}

//输出图片超链接地址
function imgurl($id): string
{
	$img = query("img", " id = '$id' ");
	return $img['url'];
}

/**
 * 输出完整路径
 *
 * @param $src
 * @return string
 */
function imgSrc($src): string
{
	return root . $src;
}

//输出图片备注
function imgtext($id): string
{
	$img = query("img", " id = '$id' ");
	return $img['text'];
}


/*列表图像替换*/
function listImg($img): string
{
	if ($img == "") {
		$html = img("d4785w5e7es");
	} else {
		$html = root . $img;
	}
	return $html;
}

/*头像输出*/
function headImg($sex, $img): string
{
	if ($img == "") {
		if ($sex == "男") {
			$html = img("replaceMan");
		} elseif ($sex == "女") {
			$html = img("replaceWoman");
		} else {
			$html = img("replaceHead");
		}
	} else {
		if (str_contains($img, "http")) {
			$r = "";
		} else {
			$r = root;
		}
		$html = $r . $img;
	}
	return $html;
}

/*图像处理函数
$data = array(
    "fileName" => "上传图片的表单文件域名称",
    "sqlSearch" => "查询图片的数据库代码",
    "sqlIn" => "数据库图片处理参数，如果是新增则是函数insert的参数，如果是更新则是函数update的参数",
    "make" => "处理方式：裁剪图像、缩放图像、空",
    "type" => "插入类型：更新图像、新增图像",
    "field" => "存放图片根目录的数据库字段名",
    "url" => "新图片保存的服务器根目录位置",
    "maxNum" => "新增图像时限定的图像总数",
    "newWidth" => "新图像的宽度",
    "newHeight" => "新图像的高度，裁剪图像时必须",
    "maxHeight" => "缩放后图片的最大高度",
);
*/
function imgUpdate($data): string
{
	//赋值
	$fileName = $data['fileName'];              //文件域名称
	$type     = $_FILES[$fileName]["type"];     //被上传文件的类型
	$tmp_name = $_FILES[$fileName]["tmp_name"]; //存储在服务器的文件的临时副本的名称
	$img      = imgType($type, $tmp_name);
	$height   = imagesy($img);
	$width    = imagesx($img);
	$con      = $GLOBALS['con'];
	//判断是否需要裁剪
	if (empty($tmp_name)) {
		$warn = "请上传图像";
	} elseif (empty($img)) {
		$warn = "不是图片或格式不对";
	} elseif ($data['make'] == "缩放图像" and $height > $data['maxHeight'] and $data['newWidth'] * $height / $width > $data['maxHeight']) {
		$warn = "图像缩放后高度仍然超过" . $data['maxHeight'] . "像素！";
	} else {
		//如果需要裁剪，则先裁剪图像
		if ($data['make'] == "裁剪图像") {
			//新建一个真彩色图像
			$newImg = imagecreatetruecolor($data['newWidth'], $data['newHeight']);
			//放置图像
			$oldRatio = $width / $height;
			$newRatio = $data['newWidth'] / $data['newHeight'];
			if ($oldRatio == $newRatio) { //宽高比一致
				imagecopyresampled($newImg, $img, 0, 0, 0, 0, $data['newWidth'], $data['newHeight'], $width, $height);
			} elseif ($oldRatio > $newRatio) { //上传的图像过宽
				$newWidth = $height * $data['newWidth'] / $data['newHeight'];
				$cutLeft  = ($width - $newWidth) / 2;
				imagecopyresampled($newImg, $img, 0, 0, $cutLeft, 0, $data['newWidth'], $data['newHeight'], $newWidth, $height);
			} elseif ($oldRatio < $newRatio) { //上传的图像过高
				$newHeight = $width * $data['newHeight'] / $data['newWidth'];
				$cutTop    = ($height - $newHeight) / 2;
				imagecopyresampled($newImg, $img, 0, 0, 0, $cutTop, $data['newWidth'], $data['newHeight'], $width, $newHeight);
			}
		} else {
			$newImg = $img;
		}
		//处理图像的数据库记录
		if ($data['type'] == "新增图像") {
			if (mysqli_num_rows(mysqli_query($con, $data['sqlSearch'])) >= $data['maxNum']) {
				$warn = "最多只能上传" . $data['maxNum'] . "张图像！";
			} else {
				$warn = insert($data['sqlIn']);
			}
		} elseif ($data['type'] == "更新图像") {
			$sql    = mysqli_query($con, $data['sqlSearch']);
			$sqlNum = mysqli_num_rows($sql); //查询出的数据库记录条数
			if (empty($sqlNum)) {
				$warn = "未找到此图片在数据库表中的记录";
			} elseif ($sqlNum > 1) {
				$warn = "数据库记录条数不止一条";
			} else {
				//如果以前上传过图像，则删除旧的图像
				$sqlArray = mysqli_fetch_array($sql);
				if (isset($sqlArray[$data['field']])) {
					unlink(serverRoot . $sqlArray[$data['field']]);
				}
				//保存图像路径到服务器
				$warn = update($data['sqlIn']);
			}
		} else {
			$warn = "未知图像处理方式";
		}
		//保存图像，如需要缩放，则缩放图像
		if (in_array($warn, array("更新成功", "新增成功"))) {
			//保存图片到服务器
			imagejpeg($newImg, serverRoot . $data['url']);
			// 释放内存
			imagedestroy($img);
			imagedestroy($newImg);
			//如果图像过大，则适当缩放图像
			if ($data['make'] == "缩放图像" and $width > $data['newWidth']) {
				jpegSmallWidth(serverRoot . $data['url'], $data['newWidth']);
			}
			$warn = "图像处理成功";
		}
	}
	//返回信息
	return $warn;
}

/*
$data = array(
    "fileName" => "上传图像的表单文件域名称",
    "width" => "图像宽度，一旦设定，图像必须按照此宽度上传",
    "height" => "图像高度，一旦设定，图像必须按照此高度上传",
    "maxHeight" => "图像最大高度，超高图片切片时只设定每张图片的最大高度，不限定图像高度",
    "maxSize" => "图像最大体积KB",
    "type" => "插入类型：更新图像、新增图像",
    "sqlSearch" => "查询图片的数据库代码",
    "sqlIn" => "数据库图片处理参数，如果是新增则是函数insert的参数，如果是更新则是函数update的参数",
    "maxNum" => "新增图像时限定的图像总数",
    "field" => "存放图片根目录的数据库字段名",
    "url" => "新图片保存的网站根目录位置",
);
*/
function imgUpdateCheck($data): string
{
	//赋值
	$fileName = $data['fileName'];              //文件域名称
	$type     = $_FILES[$fileName]["type"];     //被上传文件的类型
	$tmp_name = $_FILES[$fileName]["tmp_name"]; //存储在服务器的文件的临时副本的名称
	$size     = $_FILES[$fileName]["size"];     //当前图片体积
	$imgInfo  = getimagesize($tmp_name);        //图像信息
	$width    = $imgInfo[0];                    //当前图像宽度
	$height   = $imgInfo[1];                    //当前图像高度
	$con      = $GLOBALS['con'];
	if (empty($fileName)) {
		$warn = "请上传图像";
	} elseif (!in_array($type, array("image/jpeg", "image/pjpeg", "image/png", "image/x-png", "image/gif"))) {
		$warn = "不是图片或格式不对";
	} elseif ($data['width'] != $width) {
		$warn = "图像宽度不等于" . $data['width'] . "像素";
	} elseif ($data['height'] > 0 and $data['height'] != $height) {
		$warn = "图像高度不等于" . $data['height'] . "像素";
	} elseif (empty($data['height']) and empty($data['maxHeight'])) {
		$warn = "未设定高度";
	} elseif (empty($data['height']) and $height > $data['maxHeight']) {
		$warn = "图像超高";
	} elseif ($size > $data['maxSize'] * 1000) {
		$warn = "图像体积不得超过" . $data['maxSize'] . "KB";
	} else {
		$sql = mysqli_query($con, $data['sqlSearch']);
		$num = mysqli_num_rows($sql); //数据库中当前图像数量
		if ($data['type'] == "新增图像") {
			if ($num < $data['maxNum']) {
				$warn = insert($data['sqlIn']);
			} else {
				$warn = "最多只能上传" . $data['maxNum'] . "张图像";
			}
		} elseif ($data['type'] == "更新图像") {
			if (empty($num)) {
				$warn = "未找到需要更新的图像的数据库记录";
			} elseif ($num > 1) {
				$warn = "需要更新的图像的数据库记录不止一条";
			} else {
				//如果以前上传过图像，则删除旧的图像
				$sqlArray = mysqli_fetch_array($sql);
				if (isset($sqlArray[$data['field']])) {
					unlink(serverRoot . $sqlArray[$data['field']]);
				}
				//保存图像路径到服务器
				$warn = update($data['sqlIn']);
			}
		} else {
			$warn = "未知图像处理方式";
		}
		//处理图像
		if (in_array($warn, array("更新成功", "新增成功"))) {
			move_uploaded_file($tmp_name, serverRoot . $data['url']); //保存图片到服务器
			$warn = "图像处理成功";
		}
	}
	//返回信息
	return $warn;
}

/*判断上传的图像格式，并根据图像的地址和格式创建新图像到内存中*/
function imgType($type, $name): GdImage|bool|string
{
	if ($type == "image/jpeg" || $type == "image/pjpeg") {
		$img = imagecreatefromjpeg($name);
	} elseif ($type == "image/png" || $type == "image/x-png") {
		$img = imagecreatefrompng($name);
	} elseif ($type == "image/gif") {
		$img = imagecreatefromgif($name);
	} else {
		$img = "";
	}
	return $img;
}

/*获取图片地址并根据指定宽度强制缩放JPEG图像*/
//$ImgUrl为图片地址，$NewWidth为指定宽度
function jpegSmallWidth($ImgUrl, $NewWidth)
{
	$img       = imagecreatefromjpeg($ImgUrl);
	$height    = imagesy($img);
	$width     = imagesx($img);
	$NewHeight = $NewWidth * ($height / $width);
	//创建一个新的图像
	$SmallImg = imagecreatetruecolor($NewWidth, $NewHeight);
	//将原图像缩放并放入新图像中
	imagecopyresampled($SmallImg, $img, 0, 0, 0, 0, $NewWidth, $NewHeight, $width, $height);
	//保存图像至原图像地址
	imagejpeg($SmallImg, $ImgUrl);
	// 释放内存
	imagedestroy($SmallImg);
}
